/**
 * API测试和诊断工具
 * 用于排查待办状态更新问题
 */

import request from './request.js'

/**
 * 测试API连接性
 */
export const testApiConnection = async () => {
  try {
    console.log('开始测试API连接...')
    
    // 测试获取待办列表接口
    const response = await request.get('/api/todo')
    
    console.log('API连接测试成功:', response)
    return {
      success: true,
      message: 'API连接正常',
      data: response
    }
  } catch (error) {
    console.error('API连接测试失败:', error)
    return {
      success: false,
      message: error.message,
      error: error
    }
  }
}

/**
 * 测试认证token有效性
 */
export const testAuth = async () => {
  try {
    console.log('开始测试认证token...')
    
    const token = uni.getStorageSync('token')
    if (!token) {
      return {
        success: false,
        message: '未找到认证token',
        needLogin: true
      }
    }
    
    console.log('当前token:', token.substring(0, 20) + '...')
    
    // 测试需要认证的接口
    const response = await request.get('/api/todo/statistics')
    
    console.log('认证测试成功:', response)
    return {
      success: true,
      message: '认证token有效',
      data: response
    }
  } catch (error) {
    console.error('认证测试失败:', error)
    
    if (error.message.includes('401') || error.message.includes('未授权')) {
      return {
        success: false,
        message: '认证token已过期或无效',
        needLogin: true,
        error: error
      }
    }
    
    return {
      success: false,
      message: error.message,
      error: error
    }
  }
}

/**
 * 测试待办状态更新接口
 */
export const testToggleStatus = async (todoId) => {
  try {
    console.log('开始测试待办状态更新...')
    
    if (!todoId) {
      return {
        success: false,
        message: '缺少待办事项ID'
      }
    }
    
    // 先获取待办详情
    const todoDetail = await request.get(`/api/todo/detail/${todoId}`)
    console.log('待办详情:', todoDetail)
    
    if (!todoDetail || todoDetail.code !== 200) {
      return {
        success: false,
        message: '获取待办详情失败',
        data: todoDetail
      }
    }
    
    const todo = todoDetail.data
    const isCompleted = todo.status === 1
    
    console.log('当前状态:', isCompleted ? '已完成' : '待完成')
    
    // 测试状态切换
    let response
    if (isCompleted) {
      console.log('测试取消完成...')
      response = await request.put(`/api/todo/${todoId}/uncomplete`)
    } else {
      console.log('测试标记完成...')
      response = await request.put(`/api/todo/${todoId}/complete`)
    }
    
    console.log('状态更新响应:', response)
    
    if (response && response.code === 200) {
      return {
        success: true,
        message: '状态更新成功',
        data: response,
        originalStatus: isCompleted,
        newStatus: !isCompleted
      }
    } else {
      return {
        success: false,
        message: response?.message || '状态更新失败',
        data: response
      }
    }
  } catch (error) {
    console.error('状态更新测试失败:', error)
    return {
      success: false,
      message: error.message,
      error: error
    }
  }
}

/**
 * 完整的诊断流程
 */
export const runDiagnostics = async (todoId) => {
  console.log('开始完整诊断...')
  
  const results = {
    connection: await testApiConnection(),
    auth: await testAuth(),
    toggle: null
  }
  
  // 如果前面的测试都通过，才测试状态更新
  if (results.connection.success && results.auth.success && todoId) {
    results.toggle = await testToggleStatus(todoId)
  }
  
  // 生成诊断报告
  const report = generateDiagnosticReport(results)
  console.log('诊断报告:', report)
  
  return {
    results,
    report
  }
}

/**
 * 生成诊断报告
 */
const generateDiagnosticReport = (results) => {
  const report = {
    summary: '',
    issues: [],
    recommendations: []
  }
  
  // 检查连接
  if (!results.connection.success) {
    report.issues.push(`API连接失败: ${results.connection.message}`)
    report.recommendations.push('检查网络连接和API服务器状态')
  }
  
  // 检查认证
  if (!results.auth.success) {
    report.issues.push(`认证失败: ${results.auth.message}`)
    if (results.auth.needLogin) {
      report.recommendations.push('重新登录获取有效token')
    } else {
      report.recommendations.push('检查token格式和有效性')
    }
  }
  
  // 检查状态更新
  if (results.toggle && !results.toggle.success) {
    report.issues.push(`状态更新失败: ${results.toggle.message}`)
    report.recommendations.push('检查待办事项是否存在，用户是否有权限')
  }
  
  // 生成总结
  if (report.issues.length === 0) {
    report.summary = '所有测试通过，API功能正常'
  } else {
    report.summary = `发现 ${report.issues.length} 个问题`
  }
  
  return report
} 